package cn.fastoo.common.dao.system;


import cn.fastoo.common.entity.system.AdminSystemConfig;
import cn.fastoo.common.entity.system.AdminSystemMenu;
import cn.fastoo.common.sampleframe.dao.FastDao;
import cn.fastoo.common.sampleframe.dao.impl.FastDaoImpl;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.common.sampleframe.springside.Collections3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.*;
import java.util.stream.Collectors;


@Component
public class AdminSystemConfigDao extends FastDaoImpl<AdminSystemConfig> implements FastDao<AdminSystemConfig> {

    public Logger logger = LoggerFactory.getLogger(AdminSystemConfigDao.class);

    @Autowired
    @Qualifier("mainDS")
    private void setJt(DataSource ds){
        this.jt = new JdbcTemplate(ds);
    }

    private List<AdminSystemConfig> cache = null;
    private Map<String,String> map = null;

    @Scheduled(cron = "0/3 * * * * ?")
    private void init(){
        cache = find(new Search());
        if(Collections3.isNotEmpty(cache)){
            map = new HashMap<>();
            cache.forEach(t->{
                map.put(t.getName(),t.getValue());
            });
        }
    }

    public enum Name  {预警天数,释放天数};
    public String getValue(Name name){
        return map.getOrDefault(name.toString(),"");
    }


    public void save(List<AdminSystemConfig> rows){
        List<Object[]> args = new ArrayList<>();
        rows.forEach(t->{
            args.add(new Object[]{t.getValue(),t.getName()});
        });
        jt.batchUpdate("update admin_system_config set value = ? where name = ?",args);
    }
}
